<template>
    <div class="page">
        <!-- 头部导航 -->
        <div class="nav-header">
            <van-icon name="arrow-left" size="34" @click="goBack" />
            <div class="title">个人资料</div>
            <div></div>
        </div>

        <div class="profile-content">
            <!-- 头像编辑 -->
            <div class="profile-item avatar-item">
                <div class="item-label">头像</div>
                <div class="avatar-wrapper">
                    <img :src="avatar" alt="用户头像" class="avatar-image">
                    <label for="avatar-upload" class="upload-label">
                        <van-icon name="arrow" class="arrow-icon" />
                    </label>
                    <input 
                        id="avatar-upload"
                        type="file" 
                        accept="image/*" 
                        style="display: none;" 
                        @change="handleFileUpload"
                    />
                </div>
            </div>

            <!-- 昵称编辑 -->
            <div class="profile-item">
                <div class="item-label">昵称</div>
                <div class="nickname-wrapper">
                    <van-field
                        v-model="nickname"
                        placeholder="请输入昵称"
                        clearable
                        input-align="right"
                        :style="{ fontSize: '28px' }"
                        @blur="saveNickname"
                        maxlength="15"
                        :readonly="!isEditing"
                        :disabled="!isEditing"
                    />
                    <van-icon 
                        name="edit" 
                        class="edit-icon" 
                        color="#333" 
                        size="30" 
                        @click="startEditing"
                    />
                </div>
            </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-btn">
            <van-button 
                type="primary" 
                block 
                @click="saveProfile" 
                :style="{
                    background: isEditing ? '#FFF6B8' : '#FEE543',
                    color: '#333',
                    border: 'none'
                }"
            >保存</van-button>
        </div>
    </div>
</template>

<script>
import { Icon, Button, Field, Toast } from 'vant';
import defaultAvatar from '../../assets/images/meituan.png';

export default {
    name: 'ProfilePage',
    components: {
        [Icon.name]: Icon,
        [Button.name]: Button,
        [Field.name]: Field
    },
    data() {
        return {
            avatar: defaultAvatar,
            nickname: '',
            originalNickname: '',
            isEditing: false,
            hasChangedAvatar: false
        };
    },
    created() {
        // 从本地存储获取用户信息
        this.loadUserInfo();
    },
    methods: {
        loadUserInfo() {
            // 从本地存储获取用户昵称和头像
            this.nickname = localStorage.getItem('userNickname') || 'rlM793425663';
            this.originalNickname = this.nickname;
            
            const savedAvatar = localStorage.getItem('userAvatar');
            this.avatar = savedAvatar || defaultAvatar;
        },
        goBack() {
            // 返回上一页
            this.$router.go(-1);
        },
        handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 检查文件类型
            const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                Toast('请上传图片文件（JPG、PNG、GIF、WEBP）');
                return;
            }
            
            // 使用FileReader读取文件并转换为base64
            const reader = new FileReader();
            reader.onload = (e) => {
                this.avatar = e.target.result;
                this.hasChangedAvatar = true;
                
                Toast({
                    message: '头像已更新，点击保存生效',
                    icon: 'passed',
                    className: 'custom-toast'
                });
            };
            reader.readAsDataURL(file);
            
            // 清空文件输入框，允许重新选择同一文件
            event.target.value = '';
        },
        saveNickname() {
            if (this.nickname && this.nickname !== this.originalNickname) {
                localStorage.setItem('userNickname', this.nickname);
                Toast({
                    message: '昵称已更新',
                    icon: 'passed',
                    className: 'custom-toast'
                });
                this.originalNickname = this.nickname;
            }
            this.isEditing = false;
        },
        startEditing() {
            this.isEditing = true;
            // 使用nextTick确保DOM更新后再聚焦输入框
            this.$nextTick(() => {
                const inputEl = this.$el.querySelector('.nickname-wrapper .van-field__control');
                if (inputEl) {
                    inputEl.focus();
                }
            });
        },
        saveProfile() {
            // 保存头像和昵称
            if (this.nickname) {
                localStorage.setItem('userNickname', this.nickname);
            }
            
            // 保存头像（如果有更改）
            if (this.hasChangedAvatar) {
                localStorage.setItem('userAvatar', this.avatar);
                this.hasChangedAvatar = false;
            }
            
            // 直接返回上一页，不显示Toast
            setTimeout(() => {
                this.$router.go(-1);
            }, 1000);
        }
    }
}
</script>

<style lang="less" scoped>
.page {
    width: 750px;
    margin: 0 auto;
    background: #f5f5f5;
    min-height: 100vh;
    padding-bottom: 100px;
    font-family: "正楷";
}

.nav-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 32px;
    z-index: 100;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    .title {
        font-size: 36px;
        font-weight: 500;
    }
}

.profile-content {
    margin-top: 108px;
    background-color: #fff;
    
    .profile-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 32px;
        border-bottom: 1px solid #f5f5f5;

        .item-label {
            font-size: 30px;
            color: #333;
        }

        .item-value {
            font-size: 28px;
            color: #999;
        }

        .avatar-wrapper {
            display: flex;
            align-items: center;
            position: relative;
            
            .avatar-image {
                width: 100px;
                height: 100px;
                border-radius: 50%;
                object-fit: cover;
            }
            
            .upload-label {
                display: flex;
                align-items: center;
                cursor: pointer;
            }
            
            .arrow-icon {
                margin-left: 16px;
                color: #999;
            }
        }

        .nickname-wrapper {
            display: flex;
            align-items: center;
            flex: 1;
            justify-content: flex-end;
            
            .van-field {
                text-align: right;
                padding: 0;
                background: transparent;
                flex: 1;
                margin-right: 16px;
            }
            
            .edit-icon {
                cursor: pointer;
            }
        }
    }
    
    .avatar-item {
        padding: 20px 32px;
    }
}

.submit-btn {
    margin: 60px 32px;

    .van-button {
        height: 88px;
        font-size: 32px;
        border-radius: 44px;
    }
}

:deep(.van-field__control) {
    text-align: right;
}

:deep(.van-cell::after) {
    border: none;
}

:deep(.van-cell) {
    padding: 0;
}

:deep(.van-field__control[disabled]) {
    color: #333;
    -webkit-text-fill-color: #333;
    opacity: 1;
}
</style> 